<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of StructureMenuElement
 *
 * @author aneto
 */
class StructureMenuElement extends MenuElement{

	public function __construct($data, NavigationMenu $e, MenuElement $me = null){
		parent::__construct($data, $e, $me);

		$this->id = isset($data['id']) && !empty($data['id']) ?  $data['id'] : '';
		$this->name = isset($data['title']) && !empty($data['title']) ?  $data['title'] : '';
		$this->lft = isset($data['lft']) && !empty($data['lft']) ?  $data['lft'] : '';
		$this->rgt = isset($data['rgt']) && !empty($data['rgt']) ?  $data['rgt'] : '';

		$this->link = LinkGen::getInstance(LinkGen::STRUCTURE)->link($this->id);
		
	}


	public function getType(){
		return MenuElement::STRUCTURE_NODE;
	}


	public function isHidden(){
		return $this->fetchedData['isHidden'];
	}

	public function isActive(){
		return $this->getMenu()->isActive($this);
	}

	public function hasChildren(){
		return isset($this->fetchedData['__children']) && !empty($this->fetchedData['__children']) || isset($this->fetchedData['StructureProductGroup'][0]['ProductGroup']) && !empty($this->fetchedData['StructureProductGroup'][0]['ProductGroup']);
	}

	public function getSubElements(){
		$result = array();

		$fetchedData = $this->getFetchedData();

		//generate 
		foreach($fetchedData['__children'] as $child){
			$result[] = MenuElement::getInstance($child, MenuElement::STRUCTURE_NODE, $this->getMenu(), $this);
		}

		//product groups could be after elements
		$pg_result = array();
		if(isset($fetchedData['StructureProductGroup'] ))
			foreach($fetchedData['StructureProductGroup'] as $child){
				if(isset($child['ProductGroup']) && !empty($child['ProductGroup'])){
					$pg_result[] = MenuElement::getInstance($child, MenuElement::PRODUCT_GROUP, $this->getMenu(), $this);
					
				}
			}

		if($pg_result){
			$callback = function($a, $b){
				return $a->getLft() > $b->getLft();
			};

			usort($pg_result, $callback);
			$result = array_merge($result, $pg_result);
		}
		


		return $result;
	}


	public function getLft(){
		return $this->lft;
	}
	public function getRgt(){
		return $this->rgt;
	}

	public function getLevel(){
		$data = $this->getFetchedData();
		return $data['level'];
	}

	public function getParameter($p = 'parameter'){
		$data = $this->getFetchedData();
		return $data[$p];
	}

}
?>
